package com.wolf.gulimall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wolf.common.utils.HttpUtils;
import com.wolf.common.utils.PageUtils;
import com.wolf.common.utils.Query;
import com.wolf.gulimall.member.dao.MemberDao;
import com.wolf.gulimall.member.dao.MemberLevelDao;
import com.wolf.gulimall.member.entity.MemberEntity;
import com.wolf.gulimall.member.entity.MemberLevelEntity;
import com.wolf.gulimall.member.exception.PhoneException;
import com.wolf.gulimall.member.exception.UsernameException;
import com.wolf.gulimall.member.service.MemberService;
import com.wolf.gulimall.member.vo.MemberLoginVo;
import com.wolf.gulimall.member.vo.MemberRegisteredVo;
import com.wolf.gulimall.member.vo.SocialUserVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    private MemberLevelDao memberLevelDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 用户注册
     *
     * @param memberRegisteredVo 注册信息
     */
    @Override
    public void registered(MemberRegisteredVo memberRegisteredVo) {
        MemberEntity memberEntity = new MemberEntity();
        //设置默认等级
        MemberLevelEntity memberLevelEntity = memberLevelDao.getDefaultLevel();
        memberEntity.setLevelId(memberLevelEntity.getId());

        //进行手机号,用户名唯一性校验
        checkMobileUnique(memberRegisteredVo.getPhone());
        checkUserNameUnique(memberRegisteredVo.getUserName());

        memberEntity.setMobile(memberRegisteredVo.getPhone());
        memberEntity.setUsername(memberRegisteredVo.getUserName());
        memberEntity.setNickname(memberRegisteredVo.getUserName());

        //设置密码,密码进行加密处理,通过BCryptPasswordEncoder 进行加密解密处理
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String encode = bCryptPasswordEncoder.encode(memberRegisteredVo.getPassWord());
        memberEntity.setPassword(encode);

        baseMapper.insert(memberEntity);
    }


    /**
     * 校验手机号唯一性
     *
     * @param mobile 手机号
     */
    @Override
    public void checkMobileUnique(String mobile) {
        Integer count = baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", mobile));
        if (count > 0) {
            throw new PhoneException();
        }
    }


    /**
     * 校验用户名称唯一性
     *
     * @param userName 用户名称
     */
    @Override
    public void checkUserNameUnique(String userName) {
        Integer count = baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("username", userName));
        if (count > 0) {
            throw new UsernameException();
        }
    }

    /**
     * 用户登录
     * @param memberLoginVo 登录信息
     * @return 是否登录成功
     */
    @Override
    public MemberEntity login(MemberLoginVo memberLoginVo) {
        String userName = memberLoginVo.getUserName();
        String passWord = memberLoginVo.getPassWord();

        //在数据库中查询用户信息
        MemberEntity memberEntity = baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("username", userName).or().eq("mobile", userName));
        if(memberEntity == null){
            return null;
        }else{
            //数据库中保存的加密后的密码
            String password = memberEntity.getPassword();
            BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
            //密码匹配,利用bCryptPasswordEncoder 进行解密匹配
            boolean matches = bCryptPasswordEncoder.matches(passWord, password);
            if(matches){
                return memberEntity;
            }else{
                return null;
            }
        }
    }

    /**
     * 社交用户登录
     * @param socialUserVo 社交登录信息
     * @return 是否登录成功
     */
    @Override
    public MemberEntity login(SocialUserVo socialUserVo) throws Exception {
        //这里使用的是gitee进行社交登录的 socialUserVo 中没有保存用户的唯一ID,需要通过access_token进行查询
        String name = "";
        try {
            Map<String, String> hashMap = new HashMap<>();
            hashMap.put("access_token",socialUserVo.getAccess_token());
            HttpResponse httpResponse = HttpUtils.doGet("https://gitee.com", "/api/v5/user", "get", new HashMap<>(), hashMap);
            if(httpResponse.getStatusLine().getStatusCode()==200){
                String userInfo = EntityUtils.toString(httpResponse.getEntity());
                JSONObject jsonObject = JSON.parseObject(userInfo);
                name = jsonObject.getString("name");
                log.info("Gitee账号唯一ID为:{}",jsonObject.getLong("id"));
                socialUserVo.setUid(String.valueOf(jsonObject.getLong("id")));
            }
        }catch (Exception e){}
        //登录注册合并逻辑
        String uid = socialUserVo.getUid();
        MemberEntity memberEntity = baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", uid));
        MemberEntity entity = new MemberEntity();
        if(memberEntity != null){
            //该用户已注册,修改访问令牌信息
            entity.setId(memberEntity.getId());
            entity.setSocialUid(socialUserVo.getUid());
            entity.setExpiresIn(socialUserVo.getExpires_in());
            baseMapper.updateById(entity);

            //返回该用户信息
            memberEntity.setSocialUid(socialUserVo.getUid());
            memberEntity.setExpiresIn(socialUserVo.getExpires_in());
            return memberEntity;
        }else{
            //注册一个新账号
            entity.setSocialUid(socialUserVo.getUid());
            entity.setNickname(name);
            entity.setAccessToken(socialUserVo.getAccess_token());
            entity.setExpiresIn(socialUserVo.getExpires_in());
            entity.setCreateTime(new Date());
            baseMapper.insert(entity);
            return entity;
        }
    }

}